<template>
    <div class="e-form">
        <BillTop @cancel="onCancel"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane :label="item.label" :name="item.name" :disabled="clickTabFlag" :key="item.id" v-for="item in labelList">
                </el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%;" class="form">
                            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="240px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算编号" prop="billNo">
                                            {{ formData.billNo }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="加扣款类型:" prop="settlementType">
                                            <!-- <el-select
                                                v-model="formData.settlementType"
                                                placeholder="请选择"
                                                @change="onChangeSettlementType"
                                            >
                                                <el-option
                                                    v-for="item in jkkType"
                                                    :key="item.kvId"
                                                    :label="item.kvKey"
                                                    :value="item.kvValue"
                                                >
                                                </el-option>
                                            </el-select> -->
                                            {{getSettlementType}}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同名称" prop="contractId">
                                            <span style="color: #999;" v-if="!formData.settlementType">请先选择加扣款类型</span>
                                            <div v-else style="display: flex; width: 100%;">
                                        <el-input
                                            style="flex: 1;"
                                            placeholder="请选择合同名称"
                                            v-model="formData.contractName"
                                        >
                                            <i slot="suffix" class="el-icon-document-copy" @click="onSelectHetong"></i>
                                        </el-input>
                                        <span class="a" @click="viewHeTong(formData.contractId)" v-if="formData.contractId">查看</span>
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="外包方" prop="outsourcerId">
                                            <span>{{ formData.outsourcerName || '' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算日期:" prop="settlementDate">
                                            <el-date-picker
                                                value-format="yyyy-MM-dd"
                                                v-model="formData.settlementDate"
                                                type="date"
                                                placeholder="请选择结算日期"
                                            ></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="期数" prop="period">
                                            <span>{{ (formData.period || formData.period === 0) ? formData.period : '' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="加扣款合计" prop="amount"
                                        v-if="formData.settlementType==4||formData.settlementType==5"
                                        >
                                        <el-input
                                                type="number"
                                                placeholder="请输入加扣款合计"
                                                v-model="formData.amount"
                                                @change="settlementTypeEvent"
                                        ></el-input>
                                        <el-tooltip content="周材加扣款、设备加扣款：因分摊金额无法分摊到周材或设备上，直接在基本信息的加扣款合计填写总金额，加款填写正数，扣款填写负数" placement="top">
                                                <i class="el-icon-warning-outline greenFont"></i>
                                            </el-tooltip>
                                        </el-form-item>
                                        <el-form-item label="加扣款合计" prop="amount" v-else>
                                        <span>{{ (formData.amount || formData.amount === 0) ? formData.amount : '' }}</span>
                                        <el-tooltip content="工程加扣款、其他加扣款、材料加扣款：加扣款合计从加扣款明细获取汇总金额，不可修改，如果需要修改，请在加扣款明细修改" placement="top">
                                                <i class="el-icon-warning-outline greenFont"></i>
                                        </el-tooltip>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种" prop="currencyId">
                                            <span>{{ formData.currency || '' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            {{ selectTypeSetStateName(formData) }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="传输财务共享"
                                          :class="isFontColor ? 'redFont' : 'greenFont'">
                                            <span> {{ getEas(formData.easId) }} </span>&nbsp;
                                            <el-tooltip content="预计xxx时间传输财务" placement="top">
                                                <i class="el-icon-warning-outline greenFont"></i>
                                            </el-tooltip>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="录入机构" prop="orgId">
                                            {{ formData.orgName }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期" prop="gmtCreate">
                                            {{ showDate(formData.gmtCreate) }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注" prop="remarks">
                                            <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="请输入内容"
                                                v-model="formData.remarks"
                                                maxlength='500'
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div id="projectCon" class="con" v-if="formData.settlementType === '1'">
                        <div class="tabs-title" id="project">工程加扣款</div>
                                                <!-- {{webData}} -->
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button size="small" class="btn-greenYellow" @click="onAddList1">新增</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <div class="errorMsg" v-if="errorMsg.length>0">
                                    <span >
                                        {{ errorMsg.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    ref="tableDataShowTable"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="dtlId"
                                    :data="tableDataShow"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataShow, '_this': this, 'ref': 'tableDataShowTable' }"
                                >
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;" v-if="!formData.isSummarized">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEle(row,'1')"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="plusDeductionType" label="加/扣款类别" width="150">
                                        <template slot-scope="{ row }">
                                            {{ row.plusDeductionType === '1' ? '加款' : '扣款'}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="plusDeductionName" label="加/扣款项目" min-width="220"></el-table-column>
                                    <el-table-column prop="previousTotalAmount" align="right" label="截止上期末累计加扣款金额" width="200"></el-table-column>
                                    <el-table-column prop="amount" align="right" label="本期加扣款金额" width="200">
                                        <template slot-scope="{ row }">
                                            <el-input v-model="row.amount" v-enterFloat @change="currentAmountEvent(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="currentTotalAmount" align="right" label="截止本期末累计加扣款金额" width="200">
                                        <template slot-scope="{ row }">
                                            <div style="display: flex; justify-content: center; align-items: center;">
                                                {{row.previousTotalAmount*1 + row.amount*1}}
                                                <historyUpdateTableJs
                                                    @clickIcon="clickIcon(row)"
                                                />
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="meterialCon" class="con" v-if="formData.settlementType === '3'">
                        <div class="tabs-title" id="meterial">材料加扣款</div>
                        <CailiaoJiakoukuan :tableData.sync="tableDataCl" :formData="formData" />
                    </div>
                    <div id="otherCon" class="con" v-if="formData.settlementType === '2'">
                        <div class="tabs-title" id="other">其他加扣款</div>
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button size="small" class="btn-greenYellow" @click="onAddList1">新增</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <div class="errorMsg2" v-if="errorMsg2.length>0">
                                    <span >
                                        {{ errorMsg2.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    ref="tableDataShow2Table"
                                    key="tableRef2"
                                    border
                                    style="width: 100%"
                                    row-key="dtlId"
                                    :data="tableDataShow2"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataShow2, '_this': this, 'ref': 'tableDataShow2Table' }"
                                >
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;" v-if="!formData.isSummarized">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEle(row,'2')"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="plusDeductionType" label="加/扣款类别" width="150">
                                        <template slot-scope="{ row }">
                                            {{ row.plusDeductionType === '1' ? '加款' : '扣款'}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="plusDeductionName" label="加/扣款项目" min-width="220"></el-table-column>
                                    <el-table-column prop="previousTotalAmount" align="right" label="截止上期末累计加扣款金额" width="200"></el-table-column>
                                    <el-table-column prop="amount" align="right" label="本期加扣款金额" width="200">
                                        <template slot-scope="{ row }">
                                            <el-input v-model="row.amount" v-enterFloat  @change="table2AmountEvent(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="currentTotalAmount" align="right" label="截止本期末累计加扣款金额" width="200">
                                        <template slot-scope="{ row }">
                                            <div style="display: flex; justify-content: center; align-items: center;">
                                                {{ row.previousTotalAmount*1 + row.amount*1 }}
                                                <historyUpdateTableJs
                                                    @clickIcon="clickIcon(row)"
                                                />
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                        <div id="auditHistoryCon" class="con"  v-if="isShowHistory">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="Number(billType)" @getAuditHistory="getAuditHistory" :tableData="auditHistoryData" ref="ComExaHistory" />
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="billId" bucketName="gongchengjieshuan" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- isSystemGeneration 是否系统生成(1:是 0:否) -->
            <!-- v-if="isview==false&&[3,4,5,'3','4','5'].includes(formData.settlementType)" -->
            <ComExaButtons :auditState="auditState" @exas="exas" :canDelete="formData.isSystemGeneration !== 1" :founderId="formData.founderId" :state="formData.state" v-if="isview==false&&[3,4,5,'3','4','5'].includes(formData.settlementType)"/>
            <el-button type="primary" v-if="isShowButton" @click="onStorage">保存</el-button>
            <el-button type="danger" v-if="isShowButton" @click="onDetele">删除</el-button>
            <el-button @click="onCancel">取消</el-button>
        </div>
    </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import { openAppClient, selectDataClient, throttle, formatDate } from '@/utils/common'
// eslint-disable-next-line no-unused-vars
import { getJkkType, getJkkInfo, delJkk, getGcList, modifyGcList, getGcListOfAmount, getClList, modifyClList, modifyJkk, getClListHistory, getOtherList, modifyOtherList,
    getAuditHistoryLs, flowCommit, getCurrentState, flowUndoAudit, flownullify, getNextPeriod
} from '@/api/settlementManagement/gongchengjieshuan/jiakoukuan'
// 截止本期末累计加扣款金额 汇总历史记录
import historyUpdateTableJs from './components/historyUpdateTableJiSuanHuizong'
import AttachComp from '@/components/common/attachIndex'
//审核历史
import ComExaHistory from '@/components/common/exaHistory'
import ComExaButtons from '@/components/common/exaButtons'
import CailiaoJiakoukuan from './components/cailiaojiakoukuan'
import { mapState, mapMutations } from 'vuex'
import { uidBuilder } from '@/api/base/uid'
import '@/utils/jquery.scrollTo.min'

let oldRouter = {} // 上一个页面来源
export default {
    components: {
        historyUpdateTableJs,
        AttachComp,
        ComExaHistory,
        ComExaButtons,
        CailiaoJiakoukuan
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billType: '1097',
            flowParams: {
                'billId': '',
                'billType': '',
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            //表单数据
            formData: {},
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            auditHistoryData: [],
            auditState: {},
            rules: {
                // settlementType: [{ required: true, message: '请选择加扣款类型', trigger: ['blur', 'change'] }],
                // amount: [{ required: true, message: '请选择或填写加扣款合计', trigger: ['blur', 'change'] }],
                // contractId: [{ required: true, message: '请选择合同名称', trigger: ['blur', 'change'] }],
                // settlementDate: [{ required: true, message: '请选择结算日期', trigger: ['blur', 'change'] }],
            },
            MouseEnterId: 0,
            tableData: [], // 工程加扣款列表
            tableDataCl: [], // 材料加扣款列表
            tableData2: [], // 其他加扣款列表
            errorMsg: [],
            errorMsg2: [],
            errorList: [], // 控制导航栏感叹号的显示
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {},
            labelList: [], //标签列表
            isview: false, //是否隐藏操作按钮（fasle不隐藏,ture隐藏）
            isFontColor: true, //传输财务共享颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
            webData: '',
        }
    },
    computed: {
        ...mapState('settlementManagement', ['jkkType']),
        ...mapState('equip', ['equipData']),
        ...mapState('settlementManagement', ['jkkState']),
        ...mapState({
            stateObj: store => store.equip.equipData.state//状态
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 85 - this.lastConHeight
        },
        billId () {
            return this.$route.query.billid
        },
        tableDataShow () {
            return this.tableData.filter(item => item.changeType !== -1)
        },
        tableDataShow2 () {
            return this.tableData2.filter(item => item.changeType !== -1)
        },
        isShowHistory () {
            return ['3', '4', '5'].includes(this.formData.settlementType)
        },
        //根据选中加扣款类型改变当前状态名称
        selectTypeSetStateName () {
            return row =>{
                //工程和其他加扣款类型
                const typeObj = {
                    0: '待审',
                    1: '审核中',
                    2: '已审核',
                    3: '待汇总',
                    4: '已汇总',
                    5: '已作废',
                    9: '共享审核中',
                    '-1': '已删除'
                }
                const state = row.state
                return typeObj[state]
            }
        },
        //加扣款类型
        getSettlementType () {
            const obj = {
                '1': '工程加扣款',
                '2': '其他加扣款',
                '3': '材料加扣款',
                '4': '设备加扣款',
                '5': '周材加扣款'
            }
            return obj[this.formData.settlementType]
        },
        //工程和其他结算按钮状态
        isShowButton () {
            return this.isview == false && [1, 2, '1', '2'].includes(this.formData.settlementType) && !this.formData.isSummarized && this.formData.isSystemGeneration !== 1
            // 测试用
            // return this.isview == false && [1, 2, '1', '2'].includes(this.formData.settlementType)  && this.formData.isSystemGeneration !== 1
        },
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.flowParams.billId = this.$route.query.billid
        this.flowParams.billType = this.billType
        if(this.$route.query.isview === 'true' || this.$route.query.isview === 'false') {
            this.isview = JSON.parse(this.$route.query.isview)
        }
    },
    mounted () {
        if (!this.jkkType.length) {
            this.getType()
        }
        this.getData()
        this.auditState = this.$route.params.auditState
        if (!this.auditState) {
            this.getCurrentUnitInfo()
        }

        // 如果是新增保存后点击“继续”跳转过来的，则定位到第2个tab
        if (oldRouter.path === '/guochengJkkJieshuanAdd') {
            this.tabsName = 'baseInfo'
            this.$nextTick(() => {
                this.onChangeTab({ name: 'baseInfo' })
            })
        }
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        ...mapMutations('settlementManagement', ['setJkkType', 'setHistoryTableDataJieSuanHuiZong']),
        async getType () {
            const resData = await getJkkType({
                dicName: '工程加扣款',
                isEnable: true,
            })
            this.setJkkType(resData)
        },
        async getData () {
            const resData = await getJkkInfo({ id: this.billId })
            resData.settlementType = String(resData.settlementType)
            this.formData = resData
            this.oldType = resData.settlementType
            this.setShowLable (resData.settlementType)
            switch (this.formData.settlementType) {
            case '1':
                this.getGcListFn()
                break
            case '3':
                this.getClListFn()
                break
            case '2':
                this.getOtherListFn()
                break
            }
            // 设置滚动事件
            this.registScroll()
        },
        // 获取工程加扣款列表
        async getGcListFn () {
            const res = await getGcList({ id: this.billId })
            if (Object.prototype.toString.call(res) === '[object Object]') {
                this.tableData = res.data || []
            } else {
                this.tableData = res
            }

        },
        // 获取材料加扣款列表
        async getClListFn () {
            const res = await getClList({ id: this.billId })
            if (Object.prototype.toString.call(res) === '[object Object]') {
                this.tableDataCl = res.data || []
            } else {
                this.tableDataCl = res
            }
        },
        // 获取其它加扣款列表
        async getOtherListFn () {
            const res = await getOtherList({ id: this.billId })
            if (Object.prototype.toString.call(res) === '[object Object]') {
                this.tableData2 = res.data || []
            } else {
                this.tableData2 = res
            }
        },
        async getCurrentUnitInfo () {
            this.auditState = await getCurrentState(this.flowParams)
        },
        // 审核历史列表查询
        async getAuditHistory () {
            this.auditHistoryData = await getAuditHistoryLs(this.flowParams)
        },
        // 保存工程加扣款列表
        saveGcListFn () {
            // const tableData = this.tableData.map(item => {
            //     return {
            //         ...item,
            //     }
            // })
            // this.webData = this.tableData
            return modifyGcList(this.tableData)
        },
        // 保存材料加扣款列表
        saveClListFn () {
            const arr = this.tableDataCl.map(item => {
                const quantity = Number(item.quantity) || 0
                const price = Number(item.price) || 0
                const amount = Math.round(quantity * price * 100) / 100
                const taxRate = Number(item.taxRate) || 0
                const taxAmount = Math.round(amount * taxRate * 100) / 100
                return {
                    ...item,
                    amount,
                    taxAmount,
                    totalAmount: amount + taxAmount
                }
            })
            return modifyClList(arr)
        },
        // 保存其它加扣款列表
        saveOtherListFn () {
            // const tableData2 = this.tableData2.map(item => {
            //     return {
            //         ...item,
            //     }
            // })
            return modifyOtherList(this.tableData2)
        },
        // 保存
        async saveFn (str) {
            const promiseArr = []
            promiseArr.push(modifyJkk({
                ...this.formData,
                settlementType: Number(this.formData.settlementType)
            }))
            switch (this.formData.settlementType) {
            case '1':
                // 保存工程加扣款列表
                promiseArr.push(this.saveGcListFn())
                break
            case '3':
                // 保存材料加扣款列表
                promiseArr.push(this.saveClListFn())
                break
            case '2':
                // 保存其它加扣款列表
                promiseArr.push(this.saveOtherListFn())
                break
            }
            await Promise.all(promiseArr)
            if (str !== 'commit') {
                this.clientPop('suc', '保存成功', () => {
                    this.getData()
                })
            } else {
                if(['3', '4', '5', 3, 4, 5].includes(this.formData.settlementType)) {
                    await flowCommit(this.flowParams)
                    this.clientPop('suc', '操作成功', () => {
                        this.$router.replace('/guochengJkkJieshuanList')
                    })
                }else {
                    this.$message.warning('工程加扣款和其他加扣款不需要审核')
                }

            }
        },
        //保存按钮
        onSave (str) {
            this.$refs['ruleForm'].validate(valid => {
                if (valid) {
                    this.saveFn(str)
                }
            })
        },
        // 底部删除按钮
        onDel () {
            this.clientPop('info', this.oneDeleteErr, async () => {
                await delJkk({ id: this.billId })
                this.clientPop('suc', '删除成功', () => {
                    this.$router.replace('/guochengJkkJieshuanList')
                })
            })
        },
        async onUndo () {
            try {
                await flowUndoAudit(this.flowParams)
                this.clientPop('suc', '撤回成功', () => {
                    this.$router.replace('/guochengJkkJieshuanList')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        onNullify () {
            try {
                openAppClient('/nullifyDialog', '填写作废说明', async () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    await flownullify({
                        'billId': this.billId,
                        'billType': this.billType,
                        'nullifyCreated': '',
                        'nullifyCreator': '',
                        'nullifyCreatorId': '',
                        'nullifyDescription': auditParams.nullifyDescription,
                        'nullifyReason': auditParams.nullifyReason
                    })
                    this.clientPop('suc', '作废成功', () => {
                        this.$router.replace('/guochengJkkJieshuanList')
                    })
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        //取消按钮
        onCancel () {
            if (oldRouter.path === '/guochengJkkJieshuanList') {
                this.$router.back()
            } else {
                this.$router.replace('/guochengJkkJieshuanList')
            }
        },
        // 选择合同
        onSelectHetong () {
            console.log(this.formData.settlementType, 'this.formData.settlementType')
            const settlementType = this.formData.settlementType !== '2' ? '1' : '2' // 不是其他加扣款，1 分包合同 2 其它合同
            const settlementTitle = this.formData.settlementType !== '2' ? '选择分包合同' : '选择其他合同'
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getProjectSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: settlementType, // 接口参数(name为模拟参数)
                Title: settlementTitle // 标题
            }).then(res => {
                const val = res[0]
                this.formData.contractId = val.contractId
                this.formData.contractName = val.contractName
                this.formData.outsourcerId = val.secondPartyId
                this.formData.outsourcerName = val.secondPartyName
                this.formData.currentcyId = val.currentcyId
                this.formData.currency = val.currentcyName
                // this.formData.amount = val.contractAmount
                this.formData.period = val.period
                this.formData.currency = val.currencyName
                getNextPeriod({ contractId: val.contractId })
                    .then(res=>{
                        this.formData.period = res
                    })
            }).catch(err => {
                alert(err.message)
            })
        },
        exas (str) {
            switch (str) {
            case 'submit':
                this.onSave()
                break
            case 'submitCommit':
                this.onSave('commit')
                break
            case 'deleteData':
                this.onDel()
                break
            case 'undoAudit':
                this.onUndo()
                break
            case 'nullify':
                this.onNullify()
            }
        },
        getState (state) {
            const findObj = this.jkkState.find(item => item.value === Number(state))
            return findObj ? findObj.label : ''
        },
        getEas (eas) {
            const findObj = this.equipData.shareFrom.find(item => item.value == eas)
            return findObj ? findObj.label : ''
        },
        showDate (date) {
            return formatDate(date, 'yyyy-MM-dd')
        },
        //加扣款合计事件
        settlementTypeEvent (val) {
            if(val == 0 || !val) {
                this.$message.error('加扣款合计不能为0或者空')
                this.formData.amount = 1
            }else {
                this.formData.amount = Number(val).toFixed(2) * 1
            }
        },
        //加扣款类型
        onChangeSettlementType (e) {
            //加扣款类型切换后清空当前数据
            const obj = {
                contractName: '',
                outsourcerName: '',
                currency: '',
                contractId: '',
                amount: 0
            }
            let targetList = []
            switch (e) {
            case '1':
                this.getGcListFn()
                targetList = this.tableData
                break
            case '3':
                this.getClListFn()
                targetList = this.tableDataCl
                break
            case '2':
                this.getOtherListFn()
                targetList = this.tableData2
                break
            }
            obj.amount = targetList.reduce((a, b)=>a + b.amount, 0)
            this.formData = { ...this.formData, ...obj }
            this.setShowLable(e)
        },
        // 更新列表展示
        setShowLable (settlementType) {
            const list = []
            switch (settlementType) {
            case '1':
                list.push({ id: 1, name: 'project', label: '工程加扣款' })
                break
            case '3':
                list.push({ id: 2, name: 'meterial', label: '材料加扣款' }, { id: 10, name: 'auditHistory', label: '审核历史' })
                break
            case '4':
                list.push({ id: 10, name: 'auditHistory', label: '审核历史' })
                break
            case '5':
                list.push({ id: 10, name: 'auditHistory', label: '审核历史' })
                break
            case '2':
                list.push({ id: 3, name: 'other', label: '其他加扣款' })
                break
            }
            this.labelList = list
        },
        // 新增按钮 工程/其它加扣款
        async onAddList1 () {
            const SelectedIDs = this.tableDataShow.map(item => item.plusDeductionId)
            selectDataClient({
                SelectServiceToken: '/config/kv/getDicValue', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'type': 2, //字典类型，写死2
                    'dicName': '加款,扣款', //字典名称 必填，多个Name用逗号分隔
                    'dicKey': ''
                }),
                Title: '选择扣款类别' // 标题
            }).then(async res => {
                const ids = await uidBuilder({ num: res.length })
                // 与当前表格中数据合并，已有的不覆盖
                const arr = []
                for (let i = 0; i < res.length; i++) {
                    for (let j = i + 1; j < res.length; j++) {
                        if(res[i].kvId == res[j].kvId) {
                            res.splice(j, 1)
                            j--
                        }
                    }
                }
                res.forEach((item, index) => {
                    let findFlag
                    switch (this.formData.settlementType) {
                    case '1':
                        findFlag = this.tableData.find(subItem => subItem.plusDeductionId === item.kvId)
                        break
                    case '2':
                        findFlag = this.tableData2.find(subItem => subItem.plusDeductionId === item.kvId)
                        break
                    }
                    // 如果未找到，则添加到表格中
                    if (!findFlag) {
                        arr.push({
                            'amount': 0,
                            'billId': this.billId,
                            'changeType': 1,
                            'currentTotalAmount': 0,
                            'dtlId': ids[index],
                            'plusDeductionId': item.kvId,
                            'plusDeductionName': item.kvKey,
                            'plusDeductionType': item.kvDescription, // 1 为加款 2 为扣款
                            'previousTotalAmount': 0
                        })
                    }
                })
                const plusDeductionInfos = arr.map(item => {
                    return {
                        plusDeductionId: item.plusDeductionId
                    }
                })
                // 获取截止上期末结算金额
                const amountArr = await getGcListOfAmount({
                    contractId: this.formData.contractId,
                    orgId: this.formData.orgId,
                    settlementType: Number(this.formData.settlementType),
                    plusDeductionInfos
                })
                // this.setSelectedInfo(amountArr)
                // openAppClient('/showSelectedData', '选择结果')
                amountArr.forEach(amountItem => {
                    const findObj = arr.find(item => item.plusDeductionId === amountItem.plusDeductionId)
                    if (findObj) {
                        findObj.previousTotalAmount = amountItem.previousTotalAmount
                    }
                })
                switch (this.formData.settlementType) {
                case '1':
                    this.tableData = this.tableData.concat(arr)
                    break
                case '2':
                    this.tableData2 = this.tableData2.concat(arr)
                    break
                }
            })
        },
        deleteEle (row, type) {
            if (row.changeType === 1) {
                if(type == '1') {
                    const findIndex = this.tableData.findIndex(item => item.dtlId === row.dtlId)
                    this.tableData.splice(findIndex, 1)
                }else {
                    const findIndex = this.tableData2.findIndex(item => item.dtlId === row.dtlId)
                    this.tableData2.splice(findIndex, 1)
                }
            } else {
                row.changeType = -1
            }
            //重新计算合计金额
            if(type == '1') {
                this.formData.amount = this.tableData.reduce((a, b)=>a + (b.changeType != -1 ? Number(b.amount) : 0), 0)
            }else {
                this.formData.amount = this.tableData2.reduce((a, b)=>a + (b.changeType != -1 ? Number(b.amount) : 0), 0)
            }
        },
        async clickIcon (row) {
            const res = await getClListHistory({
                'contractId': this.formData.contractId,
                'orgId': this.formData.orgId,
                'plusDeductionId': row.plusDeductionId,
                'settlementType': Number(this.formData.settlementType),
            })
            this.setHistoryTableDataJieSuanHuiZong(res)
        },
        //根据合同类型跳转到对应合同页面
        viewHeTong (contractId) {
            let url = '/contractDefinitionShow'
            let title = '分包合同'
            //当加扣款类型为其他时进入其他合同页面，其余类型均为分包合同
            if(this.formData.settlementType == '2') {
                url = '/otherContractApplyShow'
                title = '其他合同'
            }
            openAppClient(`${url}?billid=${contractId}&isview=true`, `查看${title}`)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        setErrortMsg (msg) {
            let index = this.errorMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorMsg.push(msg)
            }
        },
        clearErrorMsg () {
            this.errorMsg = []
            this.errorMsg2 = []
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        registScroll () {
            window.removeEventListener('scroll', this.winEvent.onScroll)
            window.removeEventListener('resize', this.winEvent.onResize)
            // 保存所有tabName
            let arr = ['baseInfo', 'project', 'meterial', 'other', 'attach', 'auditHistory']
            let $idsTop = []
            const onScroll = () => {
                switch (this.formData.settlementType) {
                case '1':
                    arr = ['baseInfo', 'project', 'attach']
                    break
                case '3':
                    arr = ['baseInfo', 'meterial',  'auditHistory', 'attach']
                    break
                case '4':
                    arr = ['baseInfo', 'auditHistory', 'attach']
                    break
                case '5':
                    arr = ['baseInfo',  'auditHistory', 'attach']
                    break
                case '2':
                    arr = ['baseInfo', 'other', 'attach']
                    break
                }
                // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
                if (this.clickTabFlag) {
                    return
                }
                if (!$idsTop[$idsTop.length - 1]) {
                    $idsTop = arr.map(item => {
                        const $item = document.getElementById(item)
                        let itemTop = null
                        if ($item) {
                            itemTop = $item.offsetTop
                        }
                        return itemTop
                    })
                }
                const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
                // 倒序查找
                let curLocal = 0
                for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
                // 设置对应tabName
                this.tabsName = arr[curLocal]
            }
            this.winEvent.onScroll = throttle(onScroll, 100)
            window.addEventListener('scroll', this.winEvent.onScroll)
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            const onResize = () => {
                this.screenWidth = document.documentElement.clientWidth - this.topHeight
                this.screenHeight = document.documentElement.clientHeight - this.topHeight
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            this.winEvent.onResize = throttle(onResize, 500)
            window.addEventListener('resize', this.winEvent.onResize)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //更新加扣款合计
        upDateJKKTotal (type) {
            let total = 0
            if(type == 1) {
                this.tableDataShow.forEach(item=>{
                    total += Number(item.amount)
                })
            }else {
                this.tableDataShow2.forEach(item=>{
                    total += Number(item.amount)
                })
            }
            return total
        },
        //本期加扣款金额事件
        currentAmountEvent (row) {
            row.changeType !== 1 ? row.changeType = 2 : null
            row.amount = row.plusDeductionType == '1' ? (Number(row.amount) || 0) : ((0 - row.amount) || 0)
            row.currentTotalAmount = Number(row.previousTotalAmount) + Number(row.amount)
            this.formData.amount = this.upDateJKKTotal(1)
        },
        //其他加扣款本期金额事件
        table2AmountEvent (row) {
            row.changeType !== 1 ? row.changeType = 2 : null
            row.amount = row.plusDeductionType == '1' ? (Number(row.amount) || 0) : ((0 - row.amount) || 0)
            row.currentTotalAmount = Number(row.previousTotalAmount) + Number(row.amount)
            this.formData.amount = this.upDateJKKTotal(2)
        },
        //工程与其他加扣款页面删除
        onDetele () {
            this.clientPop('info', this.oneDeleteErr, async () => {
                await delJkk({ id: this.billId })
                this.clientPop('suc', '删除成功', () => {
                    this.$router.replace('/guochengJkkJieshuanList')
                })
            })
        },
        //工程与其他加扣款保存
        async onStorage () {
            const promiseArr = []
            promiseArr.push(modifyJkk({
                ...this.formData,
                settlementType: Number(this.formData.settlementType)
            }))
            switch (this.formData.settlementType) {
            case '1':
                // 保存工程加扣款列表
                promiseArr.push(this.saveGcListFn())
                break
            case '2':
                // 保存其它加扣款列表
                promiseArr.push(this.saveOtherListFn())
                break
            }
            await Promise.all(promiseArr)
            this.clientPop('suc', '保存成功', () => {
                this.getData()
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
